#include "TeNetMgr.h"

#include "SocketMgrLinux.h"
#include "ListenSocketLinux.h"


#define NET_CONNECT() SocketNet& rkSocketNet = *((SocketNet*)m_pkData)

struct SocketNet
{
    SocketMgr            kSocketMgr;
    ListenSocket         kSocketListen;
};


TeNetMgr::TeNetMgr()
{
    m_pkData = NULL;
}
TeNetMgr::~TeNetMgr()
{
    NET_CONNECT();
    if(m_pkData)
    {
        rkSocketNet.kSocketListen.Stop();
        rkSocketNet.kSocketMgr.Stop();
        rkSocketNet.kSocketMgr.CloseAll();
        //delete m_pkData;
    }
}

bool TeNetMgr::Init(TeNetCall* pkCall,int iThreadCount)
{
    m_pkData = new SocketNet;
    NET_CONNECT();
    if(!rkSocketNet.kSocketMgr.Init())
    {
        return false;
    }
    rkSocketNet.kSocketMgr.SetNetCall(pkCall);
    rkSocketNet.kSocketListen.SetSocketMgr(&rkSocketNet.kSocketMgr);
    return true;
}
void TeNetMgr::Update()
{
    NET_CONNECT();
    if(!rkSocketNet.kSocketListen.Active())
    {
        rkSocketNet.kSocketListen.Start();
    }
    if(!rkSocketNet.kSocketMgr.Active())
    {
        rkSocketNet.kSocketMgr.Start();
    }

    rkSocketNet.kSocketMgr.Update();
}
bool TeNetMgr::StartListen(const char* pcIP,int iPort,int iSendBufferSize,int iRecvBufferSize)
{
    NET_CONNECT();
    bool bRet = rkSocketNet.kSocketListen.StartListen(pcIP, iPort,iSendBufferSize,iRecvBufferSize);
    if(bRet)
    {
        return true;
    }
    return false;
}
bool TeNetMgr::Connect(const char* pcIP,int iPort,int iSendBufferSize,int iRecvBufferSize)
{
    NET_CONNECT();
    Socket * s = rkSocketNet.kSocketMgr.ConnectTCPSocket(pcIP, iPort,iSendBufferSize,iRecvBufferSize);
    if(!s)
    {
        return false;
    }
    return true;
}

bool TeNetMgr::SendData(int rkSock,void* pData,int iSize)
{
    NET_CONNECT();
    return rkSocketNet.kSocketMgr.SendBuffer(rkSock,pData,iSize);
}
void TeNetMgr::DisConnect(int rkSock)
{
    NET_CONNECT();
    rkSocketNet.kSocketMgr.DisConnect(rkSock);

}
